import { reqLogin, reqLogout, reqUserInfo } from '@/api/login/login'
import { defineStore } from 'pinia'
import { SET_TOKEN, GET_TOKEN, CLEAR_TOKEN } from '@/utils/token.ts'
import type { homeResponseData, loginFormType, loginResponseData, logoutResponse } from '@/api/types/loginType'
import type { UserStateType } from '../types/user'
import { constantRoute, anyRoute, asyncRoute } from '@/router/modules/router'
import router from '@/router'
// 用户请求api

const useUserStore = defineStore('User', {
    // 用户相关公共属性
    state: (): UserStateType => {
        return {
            // 用户登陆token
            token: GET_TOKEN(),
            // 用户头像
            avatar: '',
            // 用户名
            username: '',
            // 姓名
            name: '',
            // 用户权限
            role: [],
            // 用户菜单动态路由
            menuRouter: [],
            // 按钮权限
            buttons: [],
            // 部门
            department: '',
            // 创建时间
            createTime: '',
            // 最后一次登陆时间
            lastTime: ''
        }
    },
    // 异步逻辑处理
    actions: {
        // 用户登陆请求
        async useLogin(data: loginFormType) {
            const result: loginResponseData = await reqLogin(data)
            if (result.code == 200) {
                this.token = result.token  // 本地存储token
                SET_TOKEN(result.token)
                // 执行函数成功或失败都会返回promise
                return 'ok'
            } else {
                return Promise.reject(new Error(result.msg))
            }
        },
        // 用户登陆成功
        async useLoginInfo() {
            const { code, data: result, msg }: homeResponseData = await reqUserInfo()
            if (code == 200) {
                this.username = result.username
                this.avatar = result.avatar
                this.name = result.name
                this.role = result.role
                this.buttons = result.buttons
                this.department = result.department
                this.createTime = result.createTime
                this.lastTime = result.lastTime
                // 处理动态路由
                const handleRoute = result.router.map(r => {
                    return r.split('/')[1]
                })
                // 处理动态路由
                const newAsyncRoute = asyncRoute.filter((v: any) => handleRoute.includes(v.name))
                // 赋值路由
                constantRoute[1].children! = [...constantRoute[1].children!, ...newAsyncRoute];
                this.menuRouter = [...constantRoute, ...anyRoute];
                // 注册动态路由
                [...constantRoute, ...anyRoute].forEach((route: any) => {
                    router.addRoute(route)
                })
                return 'ok'
            }
            return Promise.reject(new Error(msg))
        },
        // 退出登陆
        async uselogOut() {
            const result: logoutResponse = await reqLogout()
            if (result.code == 200) {
                // 清空用户信息
                this.token = ''
                this.username = ''
                this.name = ''
                this.avatar = ''
                this.role = []
                this.menuRouter = []
                this.buttons = []
                this.department = ''
                this.createTime = ''
                this.lastTime = ''
                CLEAR_TOKEN()
                location.reload()
                return 'ok'
            } else {
                return Promise.reject(new Error(result.msg))
            }
        },
        // 更换用户头像
        changeAvatar(newUrl: string) {
            this.avatar = newUrl
        }
    },
    getters: {

    }
})

export default useUserStore